package dahua_design.model05;

import dahua_design.model02.IUser;
import dahua_design.model03.IDepartment;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @ClassName: DataAccess
 * @Description:  模式扩展-利用反射和配置文件改造抽象工厂模式
 * @Version: v1.0.0
 * @Author: tamir
 * @Date: 2022/06/01
 * Modification History:
 * Date             Author      Version     Description
 * -------------------------------------------------------------
 * 2022/06/01      tamir        v1.0.0      创建
 */
public class DataAccess {
	private static Map<String, IUser> map = new HashMap();
	private static Map<String, IDepartment> map2 = new HashMap();
	static {
		Properties p = new Properties();
		InputStream is = DataAccess.class.getClassLoader().getResourceAsStream("Sqlbean.properties");
		Properties p2= new Properties();
		InputStream is2 = DataAccess.class.getClassLoader().getResourceAsStream("DepartmentBean.properties");
		try {
			p.load(is);
			p2.load(is2);
			//遍历Properties集合对象
			Set<Object> keys = p.keySet();
			Set<Object> dkeys = p2.keySet();
			for (Object key : keys) {
				//根据键获取值（全类名）
				String className = p.getProperty((String) key);
				//获取字节码对象
				Class clazz = Class.forName(className);
				IUser obj = (IUser) clazz.newInstance();
				map.put((String)key,obj);
			}
			for (Object key : dkeys) {
				//根据键获取值（全类名）
				String className = p2.getProperty((String) key);
				//获取字节码对象
				Class clazz = Class.forName(className);
				IDepartment obj = (IDepartment) clazz.newInstance();
				map2.put((String)key,obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//根据名称获取对象
	public static IUser createUser(String name) {
		return map.get(name);
	}
	
	public static IDepartment createDepartment(String name) {
		return map2.get(name);
	}
}
